﻿using System;
using System.ComponentModel;
using System.Threading;

namespace UtilitiesLib
{
    public abstract class ObservableObject : INotifyPropertyChanged
    {
        private SynchronizationContext synchronizationContext;

        public event PropertyChangedEventHandler PropertyChanged;

        public ObservableObject()
        {
            synchronizationContext = SynchronizationContext.Current;
            if (synchronizationContext == null)
            {
                throw new Exception("No synchronization context was specified and no default synchronization context was found.");
            }
        }

        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
            {
                synchronizationContext.Post((arg) =>
                {
                    PropertyChanged(this, e);
                }, null);
            }
        }

        protected void RaisePropertyChanged(String propertyName)
        {
            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }
    }
}